function processErrorCode(data) {
    if (typeof(data) != "object") {
        data = eval("(" + data + ")");
    }
    if (data.result_code == 11120202) {
        toastr.error(data.result_msg);
        window.history.back();
    }
    if (data.result_code == 11120103) {
        toastr.error(data.result_msg);
        location.href = "/index.html?url=" + window.location.pathname + window.location.search;
    }
}

function showLogoutConfirm() {
    //alert("show logout.");
    if (window.confirm("是否要退出登录？")) {
        logout(true, false);
    }
}

function defaultError() {
    toastr.error("未知错误。");
}

function createLoadingDiv() {
    var div = $("<div>");
    div.addClass("sk-spinner sk-spinner-three-bounce");
    div.css("margin", "25% 35%");
    div.attr("id", "linda_loading_div");

    var subDiv1 = $("<div>");
    var subDiv2 = $("<div>");
    var subDiv3 = $("<div>");

    subDiv1.addClass("sk-bounce1");
    subDiv2.addClass("sk-bounce2");
    subDiv3.addClass("sk-bounce3");

    div.append(subDiv1);
    div.append(subDiv2);
    div.append(subDiv3);

    return div;
}

function hideLoadingDiv() {
    downRefreshState(true);
    $("#linda_loading_div").css("display", "none");
}

function showLoadingDiv() {
    downRefreshState(false);
    $("#linda_loading_div").css("display", "block");
}

(function ($) {
    $.getUrlParam = function (name) {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return decodeURI(r[2]);
        return null;
    }
})(jQuery);

(function ($) {
    $.parseURL2JSON = function (url) {
        //var reg_url = /^[^\?]+\?([\w\W]+)$/,
        //    reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
        //    arr_url = reg_url.exec(url),
        //    ret = {};
        //if (arr_url && arr_url[1]) {
        //    var str_para = arr_url[1], result;
        //    while ((result = reg_para.exec(str_para)) != null) {
        //        ret[result[1]] = result[2];
        //    }
        //}
        //console.log(arr_url);
        //console.log(url,"jsPageAddStack",ret);
        //return ret;
        var str=url.split("?")[1];
        var iterms = str.split("&");
        var arr,Json={};
        for(var i=0;i<iterms.length;i++){
            arr=iterms[i].split("=");
            Json[arr[0]]=arr[1];
        }
        return Json;
    }
})(jQuery);

Date.prototype.format = function (formatStr) {
    var str = formatStr;
    var Week = ['日', '一', '二', '三', '四', '五', '六'];

    str = str.replace(/yyyy|YYYY/, this.getFullYear());
    str = str.replace(/yy|YY/, (this.getYear() % 100) > 9 ? (this.getYear() % 100).toString() : '0' + (this.getYear() % 100));

    var month = this.getMonth() + 1;
    str = str.replace(/MM/, month > 9 ? month.toString() : '0' + month);
    str = str.replace(/M/g, month);

    str = str.replace(/w|W/g, Week[this.getDay()]);

    str = str.replace(/dd|DD/, this.getDate() > 9 ? this.getDate().toString() : '0' + this.getDate());
    str = str.replace(/d|D/g, this.getDate());

    str = str.replace(/hh|HH/, this.getHours() > 9 ? this.getHours().toString() : '0' + this.getHours());
    str = str.replace(/h|H/g, this.getHours());
    str = str.replace(/mm/, this.getMinutes() > 9 ? this.getMinutes().toString() : '0' + this.getMinutes());
    str = str.replace(/m/g, this.getMinutes());

    str = str.replace(/ss|SS/, this.getSeconds() > 9 ? this.getSeconds().toString() : '0' + this.getSeconds());
    str = str.replace(/s|S/g, this.getSeconds());

    return str;
};

//if(toastr != null) {
//    toastr.options = {
//        closeButton: true,
//        progressBar: false,
//        showMethod: 'slideDown',
//        timeOut: 3000,
//        preventDuplicates: false,
//        newestOnTop: true
//        //debug : true
//    };
//}

var iOSActionManager;
var activityManager;

function chat(orderStr) {

    debugAlert(orderStr);

    if (activityManager != null) {
        //alert("activityManager.startChat('" + orderStr + "'); 04-01 11:03");
        activityManager.startChat(orderStr);
    } else if (iOSActionManager != null) {
        //alert("iOSActionManager.startChat('" + orderStr + "'); 04-01 11:03");
        iOSActionManager.startChat(orderStr);
        //alert("done");

    }
}

function videoChat(orderStr) {
    //alert(account);
    //var chatInfo = {};
    //chatInfo.nick_name = alian;
    //chatInfo.order_id = orderId;
    //chatInfo.expire_time = expireTime;
    //chatInfo.total_time = totalTime;
    //chatInfo.srv_name = "video_chat";
    //chatInfo.patiend_id = patiendId;
    //chatInfo.im_account = account;

    if (activityManager != null) {
        //alert("activityManager.startVideoChat('"+JSON.stringify(chatInfo)+"'); 04-01 11:03");
        activityManager.startVideoChat(orderStr);
    } else if (iOSActionManager != null) {
        //alert("iOSActionManager.startVideoChat('"+ orderStr +"'); 04-01 11:03");
        iOSActionManager.startVideoChat(orderStr);
    }
}

function phoneChat(orderId, isDoc) {
    grey_phone_chat(orderId, function (data) {
        if (isDoc == null) {
            alert("系统正在呼叫您和医生的手机号码，请留意接听！");
        } else {
            alert("系统正在呼叫您和患者的手机号码，请留意接听！");
        }
    });
}

function openMedicineTools() {
    debugger;

    if (!hasToken()) {
        showLoginDiv();
        return;
    }

    if (activityManager != null) {
        activityManager.startMedicineTools();
    } else if (iOSActionManager != null) {
        iOSActionManager.startMedicineTools();
    } else {
        console.debug("medical tools not support!");
    }

}

function goBack() {

    if (activityManager != null) {
        activityManager.finish(1);
    } else if (iOSActionManager != null) {
        iOSActionManager.finish(1);
    } else {
        history.go(-1);
        //window.location.reload();
    }
}

function refresh_page() {
    if (activityManager != null) {
        activityManager.reload();
    } else if (iOSActionManager != null) {
        iOSActionManager.reload();
    } else {
        window.location.reload();
    }

}

function deviceLogout() {

    if (activityManager != null) {
        activityManager.logout();
    } else if (iOSActionManager != null) {
        iOSActionManager.logout();
    }
}

function refreshAllPage() {
    var refresh = 1 + (1 << 4) + (1 << 8) + (1 << 12);
    if (activityManager != null) {
        //全部刷新
        activityManager.injectRefreshWebState(refresh);
    } else if (iOSActionManager != null) {
        //全部刷新
        iOSActionManager.injectRefreshWebState(refresh);
    }
}

function refreshService() {
    var refresh = (1 << 8);
    if (activityManager != null) {
        //全部刷新
        activityManager.injectRefreshWebState(refresh);
    } else if (iOSActionManager != null) {
        //全部刷新
        //iOSActionManager.injectRefreshWebState(refresh);
    }
}

function isMobile(mobile) {
    if (mobile.length != 11) {
        return false;
    }

    var reg0 = /^13\d{5,9}$/; //130--139。至少7位
    var reg1 = /^15\d{5,9}$/; //15至少7位
    var reg2 = /^18\d{5,9}$/; //18
    var reg3 = /^14\d{5,9}$/; //14
    var reg4 = /^17\d{5,9}$/; //17

    var my = false;
    if (reg0.test(mobile))my = true;
    if (reg1.test(mobile))my = true;
    if (reg2.test(mobile))my = true;
    if (reg3.test(mobile))my = true;
    if (reg4.test(mobile))my = true;

    if (!my) {
        return false;
    }
    return true;
}


function checkMobile(mobile) {
    if (mobile.length != 11) {
        //alert("请输入有效的账号！");
        return false;
    }

    var reg0 = /^13\d{5,9}$/; //130--139。至少7位
    var reg1 = /^15\d{5,9}$/; //15至少7位
    var reg2 = /^18\d{5,9}$/; //18
    var reg3 = /^14\d{5,9}$/; //14
    var reg4 = /^17\d{5,9}$/; //17

    var my = false;
    if (reg0.test(mobile))my = true;
    if (reg1.test(mobile))my = true;
    if (reg2.test(mobile))my = true;
    if (reg3.test(mobile))my = true;
    if (reg4.test(mobile))my = true;

    if (!my) {
        //alert("请输入有效的账号！");
        //$('#login-account').focus();
        return false;
    }

    return true;
}

function encrpyMobile(mobile) {
    if (mobile == null) {
        return "";
    }
    var mobileStr = mobile.substring(0, 3);
    mobileStr = mobileStr + "****";
    mobileStr = mobileStr + mobile.substring(7);
    return mobileStr;
}

//(function (doc, win) {
//    var docEl = doc.documentElement,
//        resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize',
//        recalc = function () {
//            var clientWidth = docEl.clientWidth;
//            if (!clientWidth) return;
//            //alert("client width is : " + clientWidth);
//            docEl.style.fontSize = (clientWidth / 100) + 'px';
//        };
//
//    if (!doc.addEventListener) return;
//    win.addEventListener(resizeEvt, recalc, false);
//    doc.addEventListener('DOMContentLoaded', recalc, false);
//})(document, window);


function kickedOut() {
    alert("您的账号已在其他手机登录，如果您没有进行该操作，那么您的账号存在安全隐患请尽快修改密码！");
    logout(true, false);
}


function setCookie(key, val) {
    //修改为会话型的cookie by zhouyuan in 2016-06-27
    $.cookie(key, val);
}

function getCookie(key) {
    return $.cookie(key);
}

function showAllLine(target) {
    $(target).removeClass("only-2-line")
}

function showOnly2Line(target) {
    $(target).addClass("only-2-line")
}

function toUrl(url) {
    window.location.href = url;
}


//var colors = ['#3d4f7d','#459cdf','#1fc5db','#0b7a83','#62ba6e','#36e2be','#723092','#bb3dfa','#bfa5cc','#8a1024','#f98ea7','#fcc030'];
var colors = ['#c5ecd6', '#78d99d', '#73d4e1', '#e8cce0', '#dab3c4', '#36e2be', '#8fef9b', '#b9d1e1', '#bfa5cc', '#edbc8c', '#b0dce5', '#fcc030'];

function getRandomICSColor(id) {
    return colors[id % 12];
}

function downRefreshState(state) {
    debugAlert("refresh state " + state);
    if (activityManager != null) {
        if (state) {
            activityManager.refreshWeb("true");
        } else {
            activityManager.refreshWeb("false");
        }

    }
}

var sexArray = [];
sexArray["female"] = "女";
sexArray["male"] = "男";
sexArray[null] = "未知";

var HISTypeArray = [];
HISTypeArray[0] = "自费";
HISTypeArray[1] = "医保";
HISTypeArray[2] = "工伤";
HISTypeArray[null] = "未知";

function calculateAge(birthday) {
    var nowDate = new Date();
    var nowYear = nowDate.getFullYear();
    var nowMonth = nowDate.getMonth() + 1;
    var nowDay = nowDate.getDate();

    var birthdayDate = new Date(birthday);
    var birthdayYear = birthdayDate.getFullYear();
    var birthdayMonth = birthdayDate.getMonth() + 1;
    var birthdayDay = birthdayDate.getDate();

    var yearDiffer = nowYear - birthdayYear;
    var monthDiffer = nowMonth - birthdayMonth;
    var dayDiffer = nowDay - birthdayDay;

    monthDiffer = dayDiffer < 0 ? monthDiffer - 1 : monthDiffer;
    yearDiffer = monthDiffer < 0 ? yearDiffer - 1 : yearDiffer;

    var year = yearDiffer;
    var month = monthDiffer < 0 ? 12 + monthDiffer : monthDiffer;

    if (year < 0) {
        debugAlert("生日或者现在日期有误");
        return null;
    } else if (year == 0 && month == 0) {
        return "不足月";
    } else if (year == 0){
        return month + "月";
    } else if (year < 3 && month != 0) {
        return year + "岁" + month + "月";
    } else {
        return year + "岁";
    }
}

function getPrivatePatientName(name) {
    if (name == null || name == ""){
        return null;
    }
    return name.substring(0,1) + "**";
}

//如果是string, 日期格式为"2016-10-15 08:30"/"2016/10/15 08:30"
function getDate(date) {

    //debugger;

    if(typeof(date) == "undefined" || date == null || date == "") {
        return new Date();
    }

    if(date instanceof  Date || typeof(date) == "number") {
        return new Date(date);
    }
    else if(typeof(date) == "string") {
        //debugger;
        var year = "";
        var month = "";
        var day = "";
        var hour = "";
        var min = "";

        //debugger;

        var c = "-";
        if(date.indexOf("/") != -1) {
            c = "/";
        }

        var array = date.split(" ");
        if(typeof(array[0]) != "undefined" &&  array[0] != null &&  array[0] != "") {
            var dateArray = array[0].split(c);
            year = dateArray[0];
            month = dateArray[1];
            day = dateArray[2];
        }
        if(typeof(array[1]) != "undefined" &&  array[1] != null &&  array[0] != "") {
            var timeArray = array[1].split(":");
            hour = timeArray[0];
            min = timeArray[1];
        }

        if(year == "" && hour == "") {
            return null;
        }
        else {
            //debugAlert(new Date(year, month-1, day, hour, min, "0"));
            return new Date(year, month-1, day, hour, min, "0");
        }
    }
    else {
        return null;
    }
}

//计算字节 汉字占两个字节
function strLen(str){
    var len = 0;
    for (var i=0; i<str.length; i++) {
        var c = str.charCodeAt(i);
        //单字节加1
        if (c > 127 || c == 94) {
            len += 2;
        }
        else {
            len++;
        }
    }
    return len;
}

jQuery.fn.extend({
    radioVal: function( value ) {
        //没有参数时
        if( !arguments.length ) {
            var res = null;
            $.each(this,function(idx,node){
                node = $(node);
                var checked = node.prop("checked");

                if(checked) {
                    res = node.val();
                }
            });

            return res;
        } else {

            $.each(this,function(idx,node){
                node = $(node);

                if(node.val() == value) {
                    node.prop("checked",true);
                }
            });
        }
    }
});

function cutEMRNumber(number) {
    if(strLen(number) > 8) {
        return number.substring(0,8) + "***";
    }
    else {
        return number;
    }
}

function isNumberOrLetter(v) {
    var patt = /^[0-9a-zA-Z]*$/g;
    if(v != null && v != "" && patt.test(v)) {
        return true;
    }
    else {
        toastr.error("患者编号只能是字母与数字");
        return false;
    }
}

function isPc(){
    var agents = ["android","windows phone","iphone","ipad","ipod","symbianos"];
    for(var i=0; i<agents.length; i++){
        if(new RegExp(agents[i],"i").test(window.navigator.userAgent)){//获取代理头信息
            return false;
        }
    }
    return true;
}